import psutil
import os

# 判断文件是否存在，存在删除，没有创建，避免重复写入
def if_path():
    if os.path.exists('D:'):
        file = 'D:/本机信息.txt'
    else:
        file = 'C:/本机信息.txt'
    if os.path.exists(file):
        os.remove(file)
    try:
        openpath = open(file,mode='a',encoding='utf-8')
    except:
        exit()
    else:
        return openpath

# 写入主机名到文件
def get_host(openfile):
    openfile.write('主机名：'+os.environ.get('computername')+'\n\n')

#获取网卡名称和其ip地址以及MAC地址，不包括回环，写入文件(
def get_ip_mac(openfile):
    for i in info:
        mac = ''
        ip = ''
        for k in info[i]:
            if k.family == -1:
                mac = k.address
            if k.family == 2:
                ip  = k.address
        if ip != '127.0.0.1':
            # print('网卡名称：'+str(i)+'\n'+'IP：'+ip+'\n'+'MAC:'+mac+'\n\n')
            openfile.write('网卡名称：'+str(i)+'\n'+'IP：'+ip+'\n'+'MAC:'+mac+'\n\n')

def main():
    openfile = if_path()
    global info
    info = psutil.net_if_addrs()
    get_host(openfile)
    get_ip_mac(openfile)
    openfile.close()

if __name__ == '__main__':
    main()